package com.sk.weichat.util;

import android.media.MediaMetadataRetriever;

import java.util.HashMap;

public class VideoUtil {

    /**
     * 获取本地视频时长
     * @param videoPath
     * @return
     */
    public static int getLocalVideoDuration(String videoPath) {
        int duration;
        try {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(videoPath);
            duration = Integer.parseInt(mmr.extractMetadata
                    (MediaMetadataRetriever.METADATA_KEY_DURATION));
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return duration;
    }


    /**
     * 获取网络视频时长
     * @param mUri
     * @return
     */
    public static int getRingDuring(String mUri){
        int duration = 0;
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();

        try {
            if (mUri != null) {
                HashMap<String, String> headers=null;
                if (headers == null) {
                    headers = new HashMap<String, String>();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            }
            duration = Integer.parseInt(mmr.extractMetadata
                    (MediaMetadataRetriever.METADATA_KEY_DURATION));
        } catch (Exception ex) {
        } finally {
            mmr.release();
        }
        return duration;
    }

    /**
     * 毫秒转为 分:秒
     * @param duration
     * @return
     */
    public static String getVideoDurationStr(int duration) {
        int totalSeconds = (int) (duration / 1000);
        int seconds = totalSeconds % 60;
        int minutes = totalSeconds / 60;
        return (minutes<10 ? ("0"+minutes):minutes) + ":"+(seconds<10 ? ("0"+seconds):seconds);
    }

}
